//
//  TakingPicturesVC.m
//  YaoHeAPP
//
//  Created by mac on 15/12/28.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "TakingPicturesVC.h"
#import "Masonry.h"
#import "Define.h"
#import "MyCell.h"
#import "AFNetworking.h"
#import "Controller.h"
@interface TakingPicturesVC ()
{
   NSInteger width;
   NSInteger height;
   UIButton*delete;
    UIImageView *imageV;
    UIView*bgView;
    UITextField*remarkMsg;
    UIButton*_issueBtnImg;
    UIView*bigView;
    
    UIView*TxtView;
}
@end

@implementation TakingPicturesVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"TakingPicturesVC"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"TakingPicturesVC"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    width=self.view.frame.size.width;
    height=self.view.frame.size.height;
    _cImages = [NSMutableArray array];
    
    self.view.backgroundColor=[self colorWithR:241.0 G:241.0 B:241.0 A:1.0];
    self.view.backgroundColor=bgVCcolor;
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(60);  make.right.offset(0);
    }];
    
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"拍照发布";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(width/2-70);
        make.width.offset(150);
        make.height.offset(30);
    }];
    //返回按钮
    UIButton*leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(24);
        make.height.offset(22);
        make.bottom.offset(-12);
    }];

    
    //bigView=[[UIView alloc]initWithFrame:CGRectMake(0, 60, width, height-60)];
    [self.view addSubview:bgView];
    
    
    bgView=[[UIView alloc]init];
    bgView.frame=CGRectMake(0, 60, width, (width-80)/3*2+160);
    //bgView.backgroundColor=[UIColor yellowColor];
    [self.view addSubview:bgView];
    
    UILabel*label1=[[UILabel alloc]init];
    label1.frame=CGRectMake(15, 20, 80, 20);
    label1.text=@"拍照上传";
    label1.font=font16;
    [bgView addSubview:label1];
    
    UILabel*label2=[[UILabel alloc]init];
    label2.frame=CGRectMake(95, 20, width-100, 20);
    label2.text=@"(一次最多可上传5张)";
    label2.textColor=[UIColor lightGrayColor];
    label2.font=font16;
    [bgView addSubview:label2];
    

//表格布局加载图片
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //设置单元格的大小
    layout.itemSize = CGSizeMake((width-32)/3,(width-32)/3);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置上下左右四个方向item距离边界的长度
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    _collectionView = [[UICollectionView alloc]initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:layout];
    //_collectionView默认背景颜色是黑色
    _collectionView.backgroundColor = [UIColor whiteColor];
    //设置数据源和代理
    _collectionView.dataSource  = self;
    _collectionView.delegate = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"MyCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    _collectionView.frame=CGRectMake(0, 40, width, (width-80)/3*2+50);
    [bgView addSubview:_collectionView];

    TxtView=[[UIView alloc]init];
    TxtView.backgroundColor=[UIColor whiteColor];
    TxtView.frame=CGRectMake(0, (width-80)/3*2+100, width, 40);
    [bgView addSubview:TxtView];
    
    UILabel*remark=[UILabel new];
    remark.frame=CGRectMake(5, 10, 50, 20);
    remark.text=@"备注:";
    remark.font=font16;
    [TxtView addSubview:remark];
    
    remarkMsg=[[UITextField alloc]init];
    remarkMsg.frame=CGRectMake(55, 10, width-65, 20);
    remarkMsg.borderStyle=UITextBorderStyleNone;
    remarkMsg.placeholder=@"如有其它要求请在此填写";
    remarkMsg.font=font16;
    remarkMsg.delegate=self;
    [remarkMsg addTarget:self action:@selector(dissMiss) forControlEvents:UIControlEventEditingDidEndOnExit];
    [TxtView addSubview:remarkMsg];
    
    _issueBtnImg=[UIButton buttonWithType:UIButtonTypeCustom];
    _issueBtnImg.layer.masksToBounds=YES;
    _issueBtnImg.layer.cornerRadius=20;
    [_issueBtnImg setBackgroundImage:[UIImage imageNamed:@"orangeButton_13"] forState:UIControlStateNormal];
    [_issueBtnImg setBackgroundImage:[UIImage imageNamed:@"orangeButton_13_hl"] forState:UIControlStateHighlighted];
    [_issueBtnImg addTarget:self action:@selector(issueBtnImg) forControlEvents:UIControlEventTouchUpInside];
    [_issueBtnImg setTitle:@"立即发布求购" forState:UIControlStateNormal];
    [_issueBtnImg setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:_issueBtnImg];
    [_issueBtnImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.right.offset(-20);
        make.height.offset(40);
        make.top.equalTo(TxtView.mas_bottom).offset(20);
    }];

    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_cImages==nil) {
        return 1;
    }
    return  _cImages.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    //cell.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
    
    if (indexPath.row==_cImages.count) {
        //cell.Img.hidden=YES;
        cell.clickRemove.hidden=YES;
        cell.addImage.hidden=NO;
        cell.Img.layer.borderWidth=0.3;
        cell.Img.layer.borderColor=[UIColor lightGrayColor].CGColor;
        cell.Img.image=nil;
    }
    else{
        cell.Img.hidden=NO;
        cell.clickRemove.hidden=NO;
        cell.addImage.hidden=YES;
        cell.Img.image=_cImages[indexPath.row];
        [cell.clickRemove addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
        cell.clickRemove.tag=indexPath.row;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==_cImages.count) {
        if(_cImages.count==5)
        {
            ALERTSHOW(@"最多只能上传5张图片");
            return;
        }
        UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相册选择", nil];
        [sheet showInView:self.view];
    }
}
//移除图片的方法
-(void)remove:(UIButton*)btn
{
    [_cImages removeObjectAtIndex:btn.tag];
    [_collectionView reloadData];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
   //拍照
    if (buttonIndex== 0) {
        
        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
        if(!isCamera)
        {
            ALERTSHOW(@"无法调用相机,请检查系统设置");
            return;
        }
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.sourceType= UIImagePickerControllerSourceTypeCamera;
        _imagePickerController.delegate=self;
        //编辑模式
        _imagePickerController.allowsEditing= YES;
        [self presentViewController:_imagePickerController animated:YES completion:nil];

    }
    else if (buttonIndex == 1) {
        //从相册选择
        _imagePickerController= [[UIImagePickerController alloc] init];
        //设置picker类型
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //设置代理
        _imagePickerController.delegate = self;
        //设置图片可以修改
        _imagePickerController.allowsEditing = YES;
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }
}

#pragma mark - UIIMAGE PICKER DELEGATE
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
        if ([type isEqualToString:@"public.image"]) {
            UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
            
            UIImageWriteToSavedPhotosAlbum(image, self,
                                           @selector(image:didFinishSavingWithError:contextInfo:),
                                           nil);
        }
    }
    else{
        //NSLog(@"UIImagePickerControllerReferenceURL: %@", [info objectForKey:UIImagePickerControllerReferenceURL]);
        [_imagePickerController dismissViewControllerAnimated:YES completion:^{
            UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
            [_cImages addObject: image];
            [_collectionView reloadData];
        }];
    }
}

//点击相册页面的取消按钮返回
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [_imagePickerController dismissViewControllerAnimated:YES completion:nil];
}

 #pragma mark - 照片保存后
 - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
     if (!error) {
         [_imagePickerController dismissViewControllerAnimated:YES completion:^{
         [_cImages addObject: image];
         [_collectionView reloadData];
     }];
     }
}

//返回
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
//立即发布按钮
-(void)issueBtnImg
{
    
    [MobClick event:@"photoForRelease"];
    
//    NSLog(@"ergyerhbndfjnrgtdnbfgcbx");
    NSDictionary*dic=@{@"REMARK":remarkMsg.text};
    [Controller upImgRequestWithUrl:@"AppQuickPublish/PostSaveQuickPublish?from=app" parameters:dic image:_cImages finishBlock:^(ClassData *classData) {
        if ([classData.number integerValue]==0) {
          
            UIAlertView*alertVie=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"发布成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alertVie.tag=10;
            [alertVie show];
            
        }
        else{
            ALERTSHOW(classData.message);
        }
        
    }];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==10) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)dissMiss
{
    return;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//颜色
-(UIColor*)colorWithR:(float)r G:(float)g B:(float)b A:(float)a
{
    UIColor*color=[UIColor colorWithRed:r/255.f green:g/255.f blue:b/255.f alpha:a];
    return color;
}

//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
//    height-(width-80)/3*2+100-260
    float hy=((width-80)/3*2+230);
//    if (hy>height/2) {
        [UIView animateWithDuration:0.25 animations:^{
            self.view.frame =CGRectMake(0,height/2-hy, self.view.frame.size.width,self.view.frame.size.height);
        }];

//    }
//    else{
//        [UIView animateWithDuration:0.25 animations:^{
//            self.view.frame =CGRectMake(0,height/2-hy, self.view.frame.size.width,self.view.frame.size.height);
//        }];
//    }
    
}

//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
  [textField resignFirstResponder];
  return YES;
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.25 animations:^{
        self.view.frame =CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height);
    }];
    
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
